#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from rpy   import *
from PyQt4 import QtGui
from PyQt4 import QtCore

"""
    This class is the widget used to load data from file. At this moment
    it only read plane tables from txt files.
"""
class ImportData (QtGui.QWidget):
    def __init__(self):
        super(ImportData, self).__init__()
        
        self.init()

    def init(self):

        self.setWindowModality(2)

        self.lbl = QtGui.QLabel('File name:', self)
        self.lbl.move(10, 20)

        self.le = QtGui.QLineEdit(self)
        self.le.move(10, 40)

        self.browse_b = QtGui.QPushButton('Browse', self)
        self.browse_b.clicked.connect(self.browseFile)
        self.browse_b.move(170, 40)
 
        self.load_b = QtGui.QPushButton('Import', self)
        self.load_b.clicked.connect(self.readData)
        self.load_b.move(170, 140)
 
        self.cancel_b = QtGui.QPushButton('Cancel', self)
        self.cancel_b.clicked.connect(self.hide)
        self.cancel_b.move(170, 170)
                                                                                            
        self.resize(260, 200)
        self.setWindowTitle('Import Data')
        self.center()

    def center(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        size   = self.geometry()
        self.move((screen.width()-size.width())/2,
                (screen.height()-size.height())/2)

    def browseFile(self):

        fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '.')
        self.le.setText(str(fname))

    def readData(self):
        self.hide()

        """ 
        r.print_(r.as_data_frame(self.rData))

        f = open(fname, 'r')
        
        with f:        
            data = f.read()
            self.textEdit.setText(data) 
        """


"""
    This is the main class for R-GUI it displays the main window.
"""
class rGui(QtGui.QMainWindow):
    def __init__(self):
        super(rGui, self).__init__() 
        self.initUI()


    def initUI(self):

        """
        Atributes
        """
        self.rData = None

        """
        Window Parameters
        """
        self.resize(640, 480)
        self.center()
        self.setWindowTitle('R-GUI')
        self.setToolTip('R-GUI')

        """
        Actions
        """

        # Load data from file
        loadFile = QtGui.QAction(QtGui.QIcon('open.png'), 'Import data', self)
        loadFile.setShortcut('Ctrl+O')
        loadFile.setStatusTip('Load data from file')
        loadFile.triggered.connect(self.importWidget)

        # Quit
        quit = QtGui.QAction(QtGui.QIcon('exit.png'), 'Exit', self)
        quit.setStatusTip('Exit R-GUI')
        quit.triggered.connect(self.close)


        """
        Menu Bar
        """
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(loadFile)  
        fileMenu.addAction(quit)  

        """
        Drawing canvas parameters
        """
        self.canvas = QtGui.QPixmap(420, 340)
        self.canvas.fill()

        self.display = QtGui.QLabel(self)
        self.display.setGeometry(10, 50, 430, 390)
        self.display.setPixmap(self.canvas)

        """
        Buttons interface
        """
        self.load_b = QtGui.QPushButton('Import', self)
        self.load_b.setGeometry(10,35,90,35)
        self.load_b.setToolTip('Load data from a file')
        self.load_b.clicked.connect(self.importWidget)

        self.gen_b = QtGui.QPushButton('Generate', self)
        self.gen_b.setGeometry(100,35,90,35)
        self.gen_b.setToolTip('Genarate data stochastically')

        self.plot_b = QtGui.QPushButton('Plot', self)
        self.plot_b.setGeometry(190,35,90,35)
        self.plot_b.setToolTip('Plot data on display')
        self.plot_b.clicked.connect(self.plotData)

        self.sld = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        self.sld.setFocusPolicy(QtCore.Qt.NoFocus)
        self.sld.setGeometry(10, 430, 420, 30)
        #self.sld.valueChanged[int].connect(self.changeValue)

        """
        Widget's
        """
        self.idw = ImportData()

    def center(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        size   = self.geometry()
        self.move((screen.width() - size.width())/2,
                (screen.height() - size.height())/2)

    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, 'Message',
                "Are you sure to quit?", QtGui.QMessageBox.Yes | 
                QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def importWidget(self):
        self.idw.show()

    def plotData(self):
        r.assign('path', str(self.idw.le.text()))
        r('x <- read.table(path)')
        r.png("prueba.png")
        r('plot(x[1]$V1,x[2]$V2)')
        r.dev_off()
        self.canvas.load("prueba.png")
        self.display.setPixmap(self.canvas.scaled(420, 390))
        #set_default_mode(NO_CONVERSION)
        #self.rData = r.read_table(str(self.idw.le.text()))
        #r.print_(r.as_data_frame(self.rData))


   # def paintEvent(self, event):

        """
        qp = QtGui.QPainter()
        rectangle = QtCore.QRectF(10.0, 20.0, 80.0, 60.0)

        circle = QtGui.QPainterPath()
        circle.addEllipse(rectangle)

        qp.begin(self.canvas)

        color = [2,7,8,9,10,11,12,5,6,16]

        for x in range(1,10):
            self.drawCircle(qp, x * 35, 350 - (x * 35), x * 3, color[x-1])
        qp.fillPath(circle, QtGui.QBrush(QtGui.QColor(168, 34, 3)))
        qp.end()

        self.display.setPixmap(self.canvas)
        """

    def drawCircle(self, qp, x, y, rad, col):
        center = QtCore.QPointF(x,y)
        circle = QtGui.QPainterPath()
        circle.addEllipse(center, rad, rad)
        qp.fillPath(circle, QtGui.QBrush(QtCore.Qt.blue))
        

app = QtGui.QApplication(sys.argv)
wid = rGui()
wid.show()

sys.exit(app.exec_())

